<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- <video src="./琵琶语.mp4" controls></video> -->
    <div class="container"></div>

    <script>
      const uri = "./琵琶语.mp4";
      const container = document.querySelector(".container");
      container.style.width = "100vw";
      container.style.height = "100vh";
      setPlay(container);

      async function setPlay(container) {
        container.style.position = "relative";
        const video = document.createElement("video");

        const { width, height } = container.getBoundingClientRect();
        console.log(width, height);

        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");
        let mask = document.createElement("div");
        container.appendChild(canvas);
        container.appendChild(mask);

        // 绘制第一帧, 必须

        video.setAttribute("src", uri);
        video.currentTime = 0.001;
        // video.setAttribute("crossOrigin", "anonymous"); // 处理跨域
        // 兼容
        // video.setAttribute("autoplay", false);
        // video.setAttribute("muted", false);
        // video.setAttribute("playsinline", true);
        // video.setAttribute("webkit-playsinline", true);

        video.addEventListener("loadeddata", (r) => {
          // 绘制第一帧
          ctx.drawImage(video, 0, 0, width, height);

          // const img = document.createElement("img");
          // img.src = canvas.toDataURL("image/jpeg", 1.0);
          // mask.appendChild(img);

          // // 设置任意图片第一帧
          // video.setAttribute("poster", "./cat.jpeg");
        });

        mask.style.width = width + "px";
        mask.style.height = height + "px";
        mask.style.backgroundColor = "rgba(0, 0, 0, 0)";
        mask.style.position = "absolute";
        mask.style.top = "0px";
        mask.style.left = "0px";
        let isPlay = false;
        let timer = null;

        video.addEventListener("ended", () => {
          timer && clearInterval(timer);
          console.log("end");
        });

        mask.addEventListener("click", function () {
          if (video.paused || video.ended) {
            mask.style.backgroundColor = "rgba(0, 0, 0, 0)";
            video.play();
            timer = setInterval(() => {
              ctx.drawImage(video, 0, 0, width, height);
            }, 1000 / 30);
          } else {
            video.pause();
            timer && clearInterval(timer);
          }
        });
      }
    </script>
  </body>
</html>
